package com.ftp.longdistance.service.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author TanYongPeng
 * <p>
 * </p>
 */
@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocketService {
    private Session session;
    private static CopyOnWriteArraySet<WebSocketService> webSockets = new CopyOnWriteArraySet<>();
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSockets.add(this);
        log.info("新的连接，数量:{}",webSockets.size());
    }
    @OnClose
    public void onClose(){
        webSockets.remove(this);
        log.info("断开 总数：{}",webSockets.size());
    }
    @OnMessage
    public void onMessage(String message){
        log.info("来自客户的消息：{}",message);
    }
    public int userCount(){
        return webSockets.size();
    }
    public void sendMessage(String message){
        for (WebSocketService webSocket : webSockets) {
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
